package cn.jeeweb.modules.client.service.impl;

import cn.jeeweb.core.common.service.impl.CommonServiceImpl;
import cn.jeeweb.core.query.data.Page;
import cn.jeeweb.core.query.data.PageImpl;
import cn.jeeweb.core.query.data.Pageable;
import cn.jeeweb.core.query.data.Queryable;
import cn.jeeweb.core.query.parse.QueryToWrapper;
import cn.jeeweb.modules.client.entity.Bale;
import cn.jeeweb.modules.client.entity.ClientOrder;
import cn.jeeweb.modules.client.entity.Task;
import cn.jeeweb.modules.client.mapper.BaleMapper;
import cn.jeeweb.modules.client.mapper.ClientOrderMapper;
import cn.jeeweb.modules.client.service.IBaleService;
import cn.jeeweb.modules.client.service.IClientOrderService;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**   
 * @Title: 订单信息
 * @Description: 订单信息
 * @author zhuht
 * @date 2018-04-26 22:51:39
 * @version V1.0   
 *
 */
@Transactional
@Service("orderService_j")
public class ClientOrderServiceImpl extends CommonServiceImpl<ClientOrderMapper,ClientOrder> implements IClientOrderService {
    @Autowired
    private IBaleService baleService;
    @Override
    public Page<ClientOrder> list(Queryable queryable, Wrapper<ClientOrder> wrapper) {
        QueryToWrapper<ClientOrder> queryToWrapper = new QueryToWrapper<ClientOrder>();
        queryToWrapper.parseCondition(wrapper, queryable);
        queryToWrapper.parseSort(wrapper, queryable);
        Pageable pageable = queryable.getPageable();
        com.baomidou.mybatisplus.plugins.Page<ClientOrder> page = new com.baomidou.mybatisplus.plugins.Page<ClientOrder>(
                pageable.getPageNumber(), pageable.getPageSize());
        com.baomidou.mybatisplus.plugins.Page<ClientOrder> content = selectPage(page, wrapper,queryable.getValue("groupSearch")!=null?queryable.getValue("groupSearch").toString():null);
        return new PageImpl<ClientOrder>(content.getRecords(), queryable.getPageable(), content.getTotal());
    }

    public com.baomidou.mybatisplus.plugins.Page<ClientOrder> selectPage(com.baomidou.mybatisplus.plugins.Page<ClientOrder> page, Wrapper<ClientOrder> wrapper,String groupSearch) {
        page.setRecords(baseMapper.selectClientOrderPage(page, wrapper,groupSearch));
        return page;
    }

    //打包
    public boolean baleOrder(Map<String,Integer> num) {
        Integer max = baseMapper.getMaxNumber((new java.text.SimpleDateFormat("yyyy-MM-dd")).format(new Date()));
        num.put("num",max==0?1:max);
        //获取店铺
        List<ClientOrder> userids = baseMapper.selectShopIds();
        if(userids.size()<4){
            return false;
        }
        //每次获取1000条，每个店铺获取的条数
        int avg = new BigDecimal(100).divide(new BigDecimal(userids.size()), 0, RoundingMode.HALF_UP).intValue();
        //获取数据查询条件
        List<Map<String,String>> limits = new ArrayList<Map<String,String>>();
        //数据分组
        Map<String,List<ClientOrder>> group = new HashMap<String,List<ClientOrder>>();
        //店铺id数组
        List<String> keys = new ArrayList<String>();
        //拼写条件
        for(ClientOrder scale:userids){
            Map<String,String> map = new HashMap<String,String>();
            map.put("user", scale.getUsername());
            map.put("limit", String.valueOf(avg));
            limits.add(map);
            List<ClientOrder> list = new ArrayList<ClientOrder>();
            group.put(scale.getUsername(),list);
            keys.add(scale.getUsername());
        }
        //获取数据
        List<ClientOrder> orders = baseMapper.selectOrderByScales(limits);
        //数据分组
        for(ClientOrder or:orders){
            List<ClientOrder> list = group.get(or.getUsername());
            list.add(or);
        }
        //任务编号
        List<Bale> bales = new ArrayList<Bale>();
        List<String> orderIds = new ArrayList<String>();
        loop:while (true){
            //随机分组
            Set<String> set = new HashSet<String>();
            while(true){
                if(keys.size()<4){
                    break loop;
                }
                int r = (int) (Math.random() * keys.size());
                List<ClientOrder> list = group.get(keys.get(r));
                //数据不足是从分配表中删除
                if(list.size()<=0){
                    keys.remove(r);
                    continue;
                }

                if(keys.size()<4){
                    break loop;
                }
                set.add(keys.get(r));
                if(set.size()>=4){
                    break;
                }
            }
            Integer n =  num.get("num");
            for(String key:set){
                Bale b = new Bale();
                b.setNumber(String.valueOf(n));
                List<ClientOrder> list = group.get(key);
                b.setOrderId(list.get(0).getId());
                bales.add(b);
                orderIds.add(list.get(0).getId());
                list.remove(0);
            }
            n++;
            num.put("num",n);
        }
        baleService.insertBatch(bales);
        baseMapper.updateBatch(orderIds);
        baseMapper.updateMaxNumber(num.get("num").toString());
        return true;
    }

    public int getMaxNumber(String createDate){
        return baseMapper.getMaxNumber(createDate);
    }
    public int updateMaxNumber(String maxNumber){
        return baseMapper.updateMaxNumber(maxNumber);
    }
}
